package kk;

import java.sql.*;
import java.util.*;

public class TopicDao {
	// findALL,add,delete,update
	public List<Topic> findAll() {
		String sql = "select * from `topic`";
		PreparedStatement ps = null;
		Connection con = DBUtil.getConnection();
		List<Topic> datas = new ArrayList();
		ResultSet rs = null;
		try {
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				Topic st = new Topic();
				st.setTid(rs.getLong("tid"));
				st.setTname(rs.getString("tname"));
				datas.add(st);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, con);
		}
		return datas;
	}

	public int add(Topic s) {
		String sql = "insert into `topic`(tid,tname)values(?,?)";
		return DBUtil.executeUpdate(sql, s.getTid(), s.getTname());
	}

	public int del(Long id) {
		String sql = "delete from `topic` where tid=?";
		return DBUtil.executeUpdate(sql, id);
	}

	public int update(Topic s) {
		String sql = "update `topic` set tname=? where tid=?";
		return DBUtil.executeUpdate(sql, s.getTname(), s.getTid());
	}

	public Topic get(Long id) {
		String sql = "select from `topic` where tid=? ";
		PreparedStatement ps = null;
		Connection con = DBUtil.getConnection();
		ResultSet rs = null;
		Topic st = null;
		try {
			ps = con.prepareStatement(sql);
			ps.setLong(1, id);
			rs = ps.executeQuery();
			while (rs.next()) {
				st = new Topic();
				st.setTid(rs.getLong("tid"));
				st.setTname(rs.getString("tname"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(rs, ps, con);
		}
		return st;
	}
}
